package w4156.idog.client;

import java.util.List;

import w4156.idog.model.*;
import w4156.idog.model.User.statusType;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.*;



/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */


public class Main implements EntryPoint {

	private static final int Void = 0;
	final TestGWTAsync svc = TestGWT.Util.getInstance();
	private TextBox UserName = new TextBox();
	private PasswordTextBox PassWord = new PasswordTextBox();
	private TextBox CreateUserNameBox = new TextBox();
	private TextBox CreateUserPasswordBox = new TextBox();
	private TextBox ModifyUserNameBox = new TextBox();
	private TextBox ModifyUserPasswordBox = new TextBox();
	private TextBox ModifyUserMoneyBox = new TextBox();
	
	public int Page = 1;
	
	private String user_name;

	private String user_phone;

	private String user_eMail;

	private String user_title;

	private String user_password;

	private String user_address;

	private String user_city;

	private String user_state;

	private String user_zipcode;

	private String user_country;

	private statusType user_status;

	private String user_updatestamp;
	
	private Double user_money;
	
	private Integer user_id;
	Label user_nameL;
	  Label user_phoneL;
	  Label user_eMailL;
	  Label user_titleL;
	  Label user_passwordL;
	  Label user_addressL;
	  Label user_cityL;
	  Label user_stateL;
	  Label user_zipcodeL;
	  Label user_countryL;
	  Label user_statusL;
	  Label user_updatestampL;
	  Label user_moneyL;
	  VerticalPanel UserInformation;
	
	private User CurrentUser;
		
	private List<User> UserList;
	
	private User dealer;
	
	private User thirdUser;
	
	private User fourthUser;
	
	
	private Button loginButton;
	private FlexTable userFlexTable = new FlexTable(); //game page
	private FlexTable adminFlexTable = new FlexTable();// admin page to modify users
	private Button ReadyButton;
	private Button HitButton;
	private Button StandButton;
	private Button DoubledownButton;
	private Button SplitButton;
	private Button SurrenderButton;
	private Button ChatButton;
	private TextBox MessageBox;
	private Button LogOutButton;
	private Button bidButton;
	//private int bidMoney = 0;
	//private int myMoney = 100;
	private Timer refreshTime;
	
	
	private boolean afterBid = false;
	private Card myCurrentCard;
	private int myCardCount = 0;
	private boolean bidFirstTime = false;
	private Image card1, card2, card3, card4, card5;
	private boolean bidAfter = false;
	private boolean hitAfter = false;
	private boolean doubledownAfter = false;
	private boolean surrenderAfter = false;
	private boolean standAfter = false;
	private int modifiedUserNum = 0;
	private int deletedUserNum = 0;
	private String a, b, c, d, e;
	private boolean isCreatedAdmin = false;
	private boolean showResult = false;
	private boolean finalfirst = true;
  /**
   * 
   * This is the entry point method.
   */
  public void onModuleLoad() {
	  
	  
	  
	/*============================Login Page====================================*/
	  
	  if (Page == 1)
	  {
		  RootPanel.get().clear();
		  VerticalPanel vPanel = new VerticalPanel();
		  HorizontalPanel hPanel1 = new HorizontalPanel();
		  HorizontalPanel hPanel2 = new HorizontalPanel();
		  VerticalPanel vPanel2 = new VerticalPanel();
		  
    Image img = new Image("http://www.columbia.edu/~def2122/blackjack.jpg");
    loginButton = new Button("Login");
    
    // We can add style names
    loginButton.addStyleName("pc-template-btn");
    // or we can set an id on a specific element for styling
    img.getElement().setId("pc-template-img");
    
	Label EasyBlackJack = new Label("Easy Black Jack -- iDog");
    Label user_name = new Label("User Name");    
    Label pass_word = new Label("Password");
    
    UserName.setFocus(true);
    PassWord.setFocus(true);
    
    
    
    vPanel.setWidth("100%");
    //vPanel.setHeight("100%");
    vPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
    vPanel2.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
    vPanel2.setWidth("100%");
    hPanel1.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
    hPanel2.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
    //hPanel1.setWidth("100%");
    //hPanel2.setWidth("100%");
    
    vPanel.add(EasyBlackJack);
    vPanel.add(img);    
    hPanel1.add(user_name);
    hPanel1.add(UserName);
    hPanel2.add(pass_word);
    hPanel2.add(PassWord);
    vPanel2.add(hPanel1);
    vPanel2.add(hPanel2);
    vPanel2.add(loginButton);
    
    
    
    RootPanel.get().add(vPanel);
    RootPanel.get().add(vPanel2);
    
    // Create the dialog box
    final DialogBox dialogBox = new DialogBox();
    dialogBox.setText("Welcome to Easy Black Jack!");
    dialogBox.setAnimationEnabled(true);
    Button closeButton = new Button("Enter");
    VerticalPanel dialogVPanel = new VerticalPanel();
    dialogVPanel.setWidth("100%");
    dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
    dialogVPanel.add(closeButton);

    closeButton.addClickListener(new ClickListener() {
      public void onClick(Widget sender) {
        dialogBox.hide();
        
      }
    });

    // Set the contents of the Widget
    dialogBox.setWidget(dialogVPanel);
    
    UserName.addKeyboardListener(new KeyboardListener()
    {

		
		public void onKeyDown(Widget arg0, char arg1, int arg2) {
			if (arg1 == KEY_ENTER)
			Login();
		}

		
		public void onKeyPress(Widget arg0, char arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}

		
		public void onKeyUp(Widget arg0, char arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
    	
    });
    
    PassWord.addKeyboardListener(new KeyboardListener()
    {

		
		public void onKeyDown(Widget arg0, char arg1, int arg2) {
			if (arg1 == KEY_ENTER)
				Login();
			
		}

		
		public void onKeyPress(Widget arg0, char arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}

		
		public void onKeyUp(Widget arg0, char arg1, int arg2) {
			// TODO Auto-generated method stub
			
		}
    	
    });
    
    loginButton.addClickListener(new ClickListener() {
        public void onClick(Widget sender) {
//          dialogBox.center();
//          dialogBox.show();
            loginButton.setEnabled(false);

          Login();
          
        }
      });
	  }//end if(Page == 1)
	  /*========================End of Login Page===========================*/
	  
	  /*===========================Join Page=================================*/
	  
	  else if(Page == 2)
	  {
		  
		  RootPanel.get().clear();
		  VerticalPanel SecondPanel = new VerticalPanel(); //2nd Page
		  Label abc1 = new Label("Join a Game");
		  Button NewGame = new Button("New Game");
		  Button JoinGame = new Button("Join Game");
		  SecondPanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		  SecondPanel.setWidth("100%");
		  NewGame.setWidth("50%");
		  NewGame.setHeight("120%");
		  JoinGame.setWidth("50%");
		  JoinGame.setHeight("120%");
		  //final DialogBox NewGameDia = new DialogBox();
		  //final DialogBox JoinGameDia = new DialogBox();
		  NewGame.addClickListener(new ClickListener(){
			 public void onClick(Widget sender){
				 Page = 3;
				 onModuleLoad();
			 }
		  });
		  
		  JoinGame.addClickListener(new ClickListener(){
				 public void onClick(Widget sender){
					 
					 
					 joinTable();
					 
				 }
			  });
		  
		  SecondPanel.add(abc1);
		  //SecondPanel.add(NewGame);
		  SecondPanel.add(JoinGame);
		  
		  UserInformation = new VerticalPanel();
		  
		  user_nameL = new Label(user_name);
			user_phoneL = new Label(user_phone);
			user_eMailL = new Label(user_eMail);
			user_titleL = new Label(user_title);
			user_passwordL = new Label(user_password);
			user_addressL = new Label(user_address);
			user_cityL = new Label(user_city);
			user_stateL = new Label(user_state);
			user_zipcodeL = new Label(user_zipcode);
			user_countryL = new Label(user_country);
			user_statusL = new Label(user_status + "");
			user_updatestampL = new Label(user_updatestamp);
			user_moneyL = new Label(user_money + "");
			
			UserInformation.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
			  UserInformation.setWidth("100%");
		  UserInformation.add(user_nameL);
		  UserInformation.add(user_moneyL);
		  UserInformation.add(user_phoneL);
		  UserInformation.add(user_titleL);
		  UserInformation.add(user_passwordL);
		  UserInformation.add(user_addressL);
		  UserInformation.add(user_cityL);
		  UserInformation.add(user_stateL);
		  UserInformation.add(user_zipcodeL);
		  UserInformation.add(user_countryL);
		  UserInformation.add(user_statusL);
		  UserInformation.add(user_updatestampL);
		  
		  
		  RootPanel.get().add(SecondPanel);
		  RootPanel.get().add(UserInformation);
		  
	  }
    
	  /*========================End of Join Page===========================*/
	  
	  /*============================Game Page==============================*/
	  else if(Page == 3)
	  {
		  RootPanel.get().clear();
		  
		  userFlexTable.setText(0, 0, "Player-----");
		  userFlexTable.setText(0, 1, "Status-----");
		  userFlexTable.setText(0, 2, "Money-----");
		  userFlexTable.setText(0, 3, "Bid-----");
		  userFlexTable.setText(0, 4, "Card Number-----");
		  userFlexTable.setText(0, 5, "1st Card-----------------");
		  userFlexTable.setText(0, 6, "2nd Card-----------------");
		  userFlexTable.setText(0, 7, "3rd Card-----------------");
		  userFlexTable.setText(0, 8, "4th Card-----------------");
		  userFlexTable.setText(0, 9, "5th Card");
		  
		  
		  
		  
		  ReadyButton = new Button("Ready");
		  HitButton = new Button("Hit");
		  StandButton = new Button("Stand");
		  DoubledownButton = new Button("Double Down");
		  SplitButton = new Button("Split");
		  SurrenderButton = new Button("Surrender");
		  ChatButton = new Button("Message");
		  MessageBox = new TextBox();
		  LogOutButton = new Button("Logout");
		  bidButton = new Button("Bid $25");
		  
		  HitButton.setEnabled(false);
		  StandButton.setEnabled(false);
		  DoubledownButton.setEnabled(false);
		  SplitButton.setEnabled(false);
		  SurrenderButton.setEnabled(false);
		  bidButton.setEnabled(false);
		  LogOutButton.setEnabled(false);
		  
		  HorizontalPanel MenuPanel = new HorizontalPanel();
		  HorizontalPanel ChatPanel = new HorizontalPanel();
		  VerticalPanel GamePanel = new VerticalPanel();
		  HorizontalPanel CardPanel = new HorizontalPanel();
		  GamePanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		  GamePanel.setWidth("100%");
		  
		  card1 = new Image();
		  card2 = new Image();
		  card3 = new Image();
		  card4 = new Image();
		  card5 = new Image();
		  card1.setVisible(false);
		  card2.setVisible(false);
		  card3.setVisible(false);
		  card4.setVisible(false);
		  card5.setVisible(false);
		  
		  
		  if (myCardCount == 1)
		  {
			  //Window.alert(myCurrentCard+":"+Face(myCurrentCard)+Suit(myCurrentCard));
			  card1.setVisible(true);
			  a = "http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg/428px-Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg.png";
			  card1.setUrl(a);
			  card1.setSize("100", "150");
		  }
		  if (myCardCount == 2)
		  {
			  card1.setVisible(true);
			  card2.setVisible(true);
			  b = "http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg/428px-Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg.png";
			  card1.setUrl(a);
			  card2.setUrl(b);
			  card1.setSize("100", "150");
			  card2.setSize("100", "150");
			  
		  }
		  if (myCardCount == 3)
		  {
			  card1.setVisible(true);
			  card2.setVisible(true);
			  card3.setVisible(true);
			  c = "http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg/428px-Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg.png";
			  card1.setUrl(a);
			  card2.setUrl(b);
			  card3.setUrl(c);
			  card1.setSize("100", "150");
			  card2.setSize("100", "150");
			  card3.setSize("100", "150");
			  
		  }
		  if (myCardCount == 4)
		  {
			  card1.setVisible(true);
			  card2.setVisible(true);
			  card3.setVisible(true);
			  card4.setVisible(true);
			  d = "http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg/428px-Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg.png";
			  card1.setUrl(a);
			  card2.setUrl(b);
			  card3.setUrl(c);
			  card4.setUrl(d);
			  card1.setSize("100", "150");
			  card2.setSize("100", "150");
			  card3.setSize("100", "150");
			  card4.setSize("100", "150");
			  
			  
		  }
		  if (myCardCount == 5)
		  {
			  card1.setVisible(true);
			  card2.setVisible(true);
			  card3.setVisible(true);
			  card4.setVisible(true);
			  card5.setVisible(true);
			  e = "http://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg/428px-Cards-"+Face(myCurrentCard)+"-"+Suit(myCurrentCard)+".svg.png";
			  card1.setUrl(a);
			  card2.setUrl(b);
			  card3.setUrl(c);
			  card4.setUrl(d);
			  card5.setUrl(e);
			  card1.setSize("100", "150");
			  card2.setSize("100", "150");
			  card3.setSize("100", "150");
			  card4.setSize("100", "150");
			  card5.setSize("100", "150");
		
		  }
		  
		  
		  CardPanel.add(card1);
		  CardPanel.add(card2);
		  CardPanel.add(card3);
		  CardPanel.add(card4);
		  CardPanel.add(card5);
		  
		  MenuPanel.add(ReadyButton);
		  MenuPanel.add(HitButton);
		  MenuPanel.add(StandButton);
		  MenuPanel.add(DoubledownButton);
		  //MenuPanel.add(SplitButton);
		  //MenuPanel.add(SurrenderButton);
		  MenuPanel.add(bidButton);
		  //ChatPanel.add(ChatButton);
		  //ChatPanel.add(MessageBox);
		  GamePanel.add(userFlexTable);
		  GamePanel.add(MenuPanel);
		  GamePanel.add(ChatPanel);
		  GamePanel.add(LogOutButton);
		  GamePanel.add(CardPanel);
		  
		  RootPanel.get().add(GamePanel);
		  
		  LogOutButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				LogOut(); 
			 }
		  });
		  
		  bidButton.addClickListener(new ClickListener()
		  {
			  
			 public void onClick(Widget Sender)
			 {
				 bidButton.setEnabled(false);
				 //LogOutButton.setEnabled(false);
				 bid(25.0);
				 
			 }
		  });
		  
		  ReadyButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 ReadyButton.setEnabled(false);
				 //LogOutButton.setEnabled(false);
				 setReady();
				 
			 }
		  });
		  
		  HitButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 HitButton.setEnabled(false);
				  StandButton.setEnabled(false);
				  DoubledownButton.setEnabled(false);
				  SplitButton.setEnabled(false);
				  SurrenderButton.setEnabled(false);
				  //LogOutButton.setEnabled(false);
				  hit();
			 }
		  });
		  
		  StandButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 HitButton.setEnabled(false);
				  StandButton.setEnabled(false);
				  DoubledownButton.setEnabled(false);
				  SplitButton.setEnabled(false);
				  SurrenderButton.setEnabled(false);
				  //LogOutButton.setEnabled(false);
				  stand();
			 }
		  });
		  DoubledownButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 HitButton.setEnabled(false);
				  StandButton.setEnabled(false);
				  DoubledownButton.setEnabled(false);
				  SplitButton.setEnabled(false);
				  SurrenderButton.setEnabled(false);
				  //LogOutButton.setEnabled(false);
				  doubledown();
			 }
		  });
		  SplitButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 HitButton.setEnabled(false);
				  StandButton.setEnabled(false);
				  DoubledownButton.setEnabled(false);
				  SplitButton.setEnabled(false);
				  SurrenderButton.setEnabled(false);
			 }
		  });
		  SurrenderButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 HitButton.setEnabled(false);
				  StandButton.setEnabled(false);
				  DoubledownButton.setEnabled(false);
				  SplitButton.setEnabled(false);
				  SurrenderButton.setEnabled(false);
				  surrender();
			 }
		  });
		  ChatButton.addClickListener(new ClickListener()
		  {
			 public void onClick(Widget Sender)
			 {
				 
			 }
		  });
		  
		 refreshTime = new Timer()
		 {
			 public void run()
			 {
				 
				 if(Page == 3)
				 { 
				     showResult = false;
				     
				 if ( finalfirst && 
						 (UserList.get(0) != null && (UserList.get(0).retrieveStatus() == statusType.Win || UserList.get(0).retrieveStatus() == statusType.Stand|| UserList.get(0).retrieveStatus() == statusType.Surrender)) &&
						 (UserList.get(1) != null && (UserList.get(1).retrieveStatus() == statusType.Win || UserList.get(1).retrieveStatus() == statusType.Stand || UserList.get(1).retrieveStatus() == statusType.Surrender)) &&
						 (UserList.get(2) != null && (UserList.get(2).retrieveStatus() == statusType.Win || UserList.get(2).retrieveStatus() == statusType.Stand || UserList.get(2).retrieveStatus() == statusType.Surrender)) &&
						 (UserList.get(3) != null && (UserList.get(3).retrieveStatus() == statusType.Win || UserList.get(3).retrieveStatus() == statusType.Stand || UserList.get(3).retrieveStatus() == statusType.Surrender)))
				 {		
					 //Window.alert("I am bug if not show at the final result");
					 showResult = true;
					 getUserList();
					 //showResult();
					 
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					  bidButton.setEnabled(false);
					  LogOutButton.setEnabled(true);
					  
					  finalfirst = false;
					 return;
				 }
				 //Window.alert("Here");
				 if (finalfirst)//ensure only once getUserList() after final result
				 {
					 
				 getUserList();
			     refreshTable();
				 }
				 
				 if (UserList.get(0) != null && UserList.get(0).retrieveStatus() == statusType.MyTurn)
				 {
					 LogOutButton.setEnabled(false);
					 
					 if (bidFirstTime)
					 {
					 bidButton.setEnabled(true);
					 }
					 //Window.alert("OK");
					 
					 if (bidAfter || hitAfter || standAfter || doubledownAfter || surrenderAfter)
					 {
						 HitButton.setEnabled(false);
						  StandButton.setEnabled(false);
						  DoubledownButton.setEnabled(false);
						  SplitButton.setEnabled(false);
						  SurrenderButton.setEnabled(false);
						  
					 }
//					 if (surrenderAfter)
//					 {
//						 getUserList();
//						 refreshTable();
//					 }
					 
					 else if(afterBid && myCardCount != 5)
					 {
						 HitButton.setEnabled(true);
						  StandButton.setEnabled(true);
						  DoubledownButton.setEnabled(true);
						  SplitButton.setEnabled(true);
						  SurrenderButton.setEnabled(true);
						  //LogOutButton.setEnabled(false);
					 }
					 
					 
					 
					 
					 
					 if (myCardCount == 5)
					 {
						  HitButton.setEnabled(false);
						  StandButton.setEnabled(true);
						  DoubledownButton.setEnabled(false);
						  SplitButton.setEnabled(false);
						  SurrenderButton.setEnabled(false);
						  //LogOutButton.setEnabled(false);
					 }
					 
				 }
				 else if (UserList.get(0) != null && UserList.get(0).retrieveStatus() == statusType.Stand)
				 {
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					  LogOutButton.setEnabled(false);
				 }
				 else if (UserList.get(0) != null && UserList.get(0).retrieveStatus() == statusType.Surrender)
				 {
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
				 }
				 else if (UserList.get(0) != null && UserList.get(0).retrieveStatus() != statusType.MyTurn)
				 {
					 if (UserList.get(0) != null && UserList.get(0).retrieveStatus() != statusType.Pending)
					 {
					 ReadyButton.setEnabled(false);
					 LogOutButton.setEnabled(false);
					 }
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					 //LogOutButton.setEnabled(false);
				 }
				 
				 
				 bidAfter = false;
				 hitAfter = false;
				 standAfter = false;
				 doubledownAfter = false;
				 surrenderAfter = false;
				 }
				 
				 
				 else
					 return;
			 }
		 };
		  refreshTime.scheduleRepeating(5000);
	  }
	  /*========================End of Game Page============================*/
	  /*========================Start of Admin: 2 functions Page============================*/
	  else if (Page == 4)
	  {
		  RootPanel.get().clear();
		  VerticalPanel AdministrationPanel = new VerticalPanel();
		  AdministrationPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		  AdministrationPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		  AdministrationPanel.setWidth("100%");
		  Label BasicOperation = new Label("Admin's Operation(1): Create User");
		  Label CreateUserName = new Label("Create User Name");
		  Label CreateUserPassword = new Label("Create User Password");
		  CheckBox AdminCheckBox = new CheckBox("Is Administrator");
		  AdminCheckBox.setChecked(false);
		  Label AdminModifyUser = new Label("Admin's Operation(2): Modify Users' Information");
		  
		  Button CreateUserButton = new Button("Create User");
		  Button getAllUserListButton = new Button ("Get All Users List");
		  Button adminLogoutButton = new Button("Logout");
		   
		  AdministrationPanel.add(BasicOperation);
		  AdministrationPanel.add(CreateUserName);
		  AdministrationPanel.add(CreateUserNameBox);
		  AdministrationPanel.add(CreateUserPassword);
		  AdministrationPanel.add(CreateUserPasswordBox);
		  AdministrationPanel.add(AdminCheckBox);
		  AdministrationPanel.add(CreateUserButton);
		  AdministrationPanel.add(AdminModifyUser);
		  AdministrationPanel.add(getAllUserListButton);
		  AdministrationPanel.add(adminLogoutButton);
		  RootPanel.get().add(AdministrationPanel);
		  
		  final DialogBox UserCreated_dialogBox = new DialogBox();
		    UserCreated_dialogBox.setText("User Created");
		    UserCreated_dialogBox.setAnimationEnabled(true);
		    Button LogoutAdminButton = new Button("LogoutAdmin");
		    VerticalPanel UserCreated_dialogVPanel = new VerticalPanel();
		    UserCreated_dialogVPanel.setWidth("100%");
		    UserCreated_dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		    UserCreated_dialogVPanel.add(LogoutAdminButton);
		    
		    AdminCheckBox.addClickListener(new ClickListener(){

				
				public void onClick(Widget arg0) {
					isCreatedAdmin = true;
					
				}
		    	
		    });
		    getAllUserListButton.addClickListener(new ClickListener()
		    {

				
				public void onClick(Widget arg0) {
					Page = 5;
					getUserList();
					onModuleLoad();
				}
		    	
		    });
		    
		    
		    adminLogoutButton.addClickListener(new ClickListener()
		    {
				public void onClick(Widget arg0) {
					LogOut();
					
				}
		    	
		    });
		    LogoutAdminButton.addClickListener(new ClickListener() {
		      public void onClick(Widget sender) {
		        UserCreated_dialogBox.hide();
		        LogOut();
		        
		      }
		    });
		    
		  CreateUserButton.addClickListener(new ClickListener() {
		        public void onClick(Widget sender) {
		          UserCreated_dialogBox.center();
		          UserCreated_dialogBox.show();
		          CreateUser();
		          isCreatedAdmin = false;
		          
		        }
		      });
		  UserCreated_dialogBox.setWidget(UserCreated_dialogVPanel);
	  }
	  
	  /*========================End of Admin Page============================*/
	  /*========================Start of Admin User List Page============================*/
	  else if (Page == 5)
	  {
		  RootPanel.get().clear();
		  VerticalPanel userListVpanel = new VerticalPanel();
		  userListVpanel.setHorizontalAlignment(HorizontalPanel.ALIGN_CENTER);
		  userListVpanel.setWidth("100%");
		  Label AllUserListHere = new Label("Here is the List of All Users:");
		  adminFlexTable.setText(0, 0, "UserName");
		  adminFlexTable.setText(0, 1, "Password");
		  adminFlexTable.setText(0, 2, "Money");
		  adminFlexTable.setText(0, 3, "Modify");
		  adminFlexTable.setText(0, 4, "Delete");
		  Button adminLogoutButton = new Button("Logout");
		  userListVpanel.add(AllUserListHere);
		  userListVpanel.add(adminFlexTable);
		  userListVpanel.add(adminLogoutButton);
		  RootPanel.get().add(userListVpanel);
		  adminLogoutButton.addClickListener(new ClickListener()
		    {
				public void onClick(Widget arg0) {
					LogOut();
					
				}
		    	
		    });
		  
	  }
	  /*========================End of Admin User List Page============================*/
	  /*========================Start of Admin Modify User Page============================*/
	  else if (Page == 6)
	  {
		  
		  RootPanel.get().clear();
		  
		  VerticalPanel AdministrationPanel = new VerticalPanel();
		  AdministrationPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		  AdministrationPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		  AdministrationPanel.setWidth("100%");
		  Label ModifyUserName = new Label("Modify User Name");
		  Label ModifyUserPassword = new Label("Modify User Password");
		  Label ModifyUserMoney = new Label("Modify User Money");
		  Button ModifyUserButton = new Button("Save Modified User Information");
		  Button adminLogoutButton = new Button("Logout");
		  AdministrationPanel.add(ModifyUserName);
		  AdministrationPanel.add(ModifyUserNameBox);
		  ModifyUserNameBox.setText(UserList.get(modifiedUserNum).getName());
		  AdministrationPanel.add(ModifyUserPassword);
		  AdministrationPanel.add(ModifyUserPasswordBox);
		  ModifyUserPasswordBox.setText(UserList.get(modifiedUserNum).getPassword());
		  AdministrationPanel.add(ModifyUserMoney);
		  AdministrationPanel.add(ModifyUserMoneyBox);
		  ModifyUserMoneyBox.setText(UserList.get(modifiedUserNum).getMoney() + "");
		  AdministrationPanel.add(ModifyUserButton);
		  AdministrationPanel.add(adminLogoutButton);
		  
		  ModifyUserButton.addClickListener(new ClickListener()
		  {

			public void onClick(Widget arg0) {
				modifyUser(UserList.get(modifiedUserNum));
				
			}
			  
		  });
		  adminLogoutButton.addClickListener(new ClickListener()
		    {
				public void onClick(Widget arg0) {
					LogOut();
					
				}
		    	
		    });
		  
		  RootPanel.get().add(AdministrationPanel);
	  }
	  /*========================End of Admin Modify User Page============================*/
  }//end onModuleLoad
  
  
  Timer refreshTimer = new Timer(){
	    
  	public void run()
  	{
  		//onModuleLoad();
  	}
  };
  
  
  
  private void Login() {
		String Login_username = UserName.getText();
		String Login_password = PassWord.getText();
		UserName.setFocus(true);
		PassWord.setFocus(true);
		if (!Login_username.matches("^[0-9a-zA-Z\\.]{1,10}$")) {
//			Window.alert("' " + Login_username + " ' is not a valid symbol.");
			UserName.selectAll();
			loginButton.setEnabled(true);
			return;
		}
		UserName.setText("");
		PassWord.setText("");
		svc.authenticate(Login_username, Login_password,
				new AsyncCallback<User>() {

					/*
					 * if (Login_username.matches("admin") &&
					 * Login_password.matches("adminadmin")) arg1 = true; else
					 * arg1 = false;
					 */

					public void onFailure(Throwable arg0) {
						Window.alert(arg0.getMessage());
						loginButton.setEnabled(true);
					}

					public void onSuccess(User user) {
						if (user == null) 
						{
							Window.alert("login failed");
							loginButton.setEnabled(true);
						} 
						else if (user.isAdmin()) 
						{
							Window.alert("Welcome Admin");
							CurrentUser = user;

							Page = 4;
							user_name = CurrentUser.getName();
							user_phone = CurrentUser.getPhone();
							user_eMail = CurrentUser.getEMail();
							user_title = CurrentUser.getTitle();
							user_password = CurrentUser.getPassword();
							user_address = CurrentUser.getAddress();
							user_city = CurrentUser.getCity();
							user_state = CurrentUser.getState();
							user_zipcode = CurrentUser.getZipcode();
							user_country = CurrentUser.getCountry();
							user_status = CurrentUser.retrieveStatus();
							user_updatestamp = CurrentUser.getUpdatestamp();
							user_money = CurrentUser.getMoney();
							user_id = CurrentUser.getObjid();
							onModuleLoad();
						}
						else 
						{
							
							
							CurrentUser = user;
							Page = 2;
							//Page = 4;
							user_name = CurrentUser.getName();
							user_phone = CurrentUser.getPhone();
							user_eMail = CurrentUser.getEMail();
							user_title = CurrentUser.getTitle();
							user_password = CurrentUser.getPassword();
							user_address = CurrentUser.getAddress();
							user_city = CurrentUser.getCity();
							user_state = CurrentUser.getState();
							user_zipcode = CurrentUser.getZipcode();
							user_country = CurrentUser.getCountry();
							user_status = CurrentUser.retrieveStatus();
							user_updatestamp = CurrentUser.getUpdatestamp();
							user_money = CurrentUser.getMoney();
							user_id = CurrentUser.getObjid();
							
							onModuleLoad();
							
							
							
						}
						Window.alert("Welcome "+user.getName()+" !!!");
						
						
						


						// TODO Auto-generated method stub

					}
				});// end authenticate
		/*
		 * svc.testEBJ(new AsyncCallback<String>() { public void
		 * onFailure(Throwable arg0) { Window.alert("Failed to make RPC call");
		 * } public void onSuccess(String arg0) { Window.alert(arg0); }
		 * 
		 * });
		 */

	}// end Login
  
  private void CreateUser()
  {
	  	final String create_username = CreateUserNameBox.getText();
		final String create_password = CreateUserPasswordBox.getText();
		User CreatedUser = new User();
		CreatedUser.setName(create_username);
		CreatedUser.setPassword(create_password);
		if (isCreatedAdmin)
		{
		CreatedUser.setAdmin(true);
		
		}
		
		
	  
	   svc.createUser(CreatedUser, new AsyncCallback<Void>() 
	   {

		
		public void onFailure(Throwable arg0) {
		
			
		}

		
		public void onSuccess(Void arg0) {
		
			
			
		}
		   
	   });
  }
  private void LogOut()
  {
	  	
	  svc.logout(new AsyncCallback<Void>()
			  {

				
				public void onFailure(Throwable arg0) {
					Window.alert(arg0.getMessage());
					
				}

				
				public void onSuccess(Void arg0) {
					
					Window.alert("Logout Successful");
					
					if (Page == 3)
					reset();
					
					Page = 1;
					UserList = null;
					CurrentUser = null;
/*					
					private String user_name;

					private String user_phone;

					private String user_eMail;

					private String user_title;

					private String user_password;

					private String user_address;

					private String user_city;

					private String user_state;

					private String user_zipcode;

					private String user_country;

					private statusType user_status;

					private String user_updatestamp;
					
					private Double user_money;
					
					private Integer user_id;
*/					
					finalfirst = true;
			        RootPanel.get().clear();
			        onModuleLoad();
  
				}
		  
			  });
  }
  
  
  
  public void getUserList() {
	  
	  
		svc.getUserList(new AsyncCallback<List<User>>()
				{

					
					public void onFailure(Throwable arg0) {
				Window.alert(arg0.getMessage());
				Page = 1;
				onModuleLoad();
			}

			public void onSuccess(List<User> user_List) {
				/*
				 * Window.alert(User_List.size() + "\n" +
				 * User_List.get(0).getName() + "\n" +
				 * User_List.get(1).getName());
				 */
				if (user_List != null)
				{
					UserList = user_List;
					
				}
					int size = user_List.size();
				if (Page == 5 && user_List != null)//admin page
				{
					 Button modifyButton [] = new Button [size+1];
					 Button deleteButton [] = new Button [size+1];
					for ( int i = 1; i <= size; i++)
					{	
					adminFlexTable.setText(i, 0, user_List.get(i - 1).getName());
					adminFlexTable.setText(i, 1, user_List.get(i-1).getPassword());
					Double money = user_List.get(i - 1).getMoney();
					adminFlexTable.setText(i, 2, money.toString());
					modifyButton [i] = new Button ("Modify");
					adminFlexTable.setWidget(i, 3, modifyButton [i]);
					deleteButton [i] = new Button("Delete");
					adminFlexTable.setWidget(i, 4, deleteButton [i]);
					
					final int j = i;
					final int size1 = size;
					modifyButton [i].addClickListener(new ClickListener()
					{

						
						public void onClick(Widget arg0) {
							
							modifiedUserNum = j-1;
							Window.alert("Modify User " + j);
							
							Page = 6;
							onModuleLoad();
						}
						
					});
					
					deleteButton [i].addClickListener(new ClickListener()
					{

						
						public void onClick(Widget arg0) {
							deletedUserNum = j-1;
							deleteUser(UserList.get(j-1));
							Page = 5;
							adminFlexTable.clear();
							//getUserList();
							//onModuleLoad();
							adminFlexTable.removeRow(size1);
							
						}
						
					});
					}
					
					
						
					
					
				}
				else if (showResult && Page == 3 && user_List != null)//show result
				{
					for (int i = 1; i <= size; i++) {
						userFlexTable.setText(i, 0, user_List.get(i - 1).getName());
						
						statusType status = user_List.get(i - 1).retrieveStatus();
						if (status != null)
							userFlexTable.setText(i, 1, status.toString());
						
						Double money = user_List.get(i - 1).getMoney();
						
						if (money != null)
						{
							if (i == 2)
								userFlexTable.setText(i, 2, "N/A");
							else
							userFlexTable.setText(i, 2, money.toString());
						}
						Double bidAmount = user_List.get(i - 1).retrieveBidAmount();
						if (bidAmount != null)
							userFlexTable.setText(i, 3, bidAmount.toString());
						
						Integer cardNumber = user_List.get(i - 1).retrieveCardNumbers();
						if (cardNumber != null)
							userFlexTable.setText(i, 4, cardNumber.toString());
					}
					
					
					Window.alert("Game Over !!!!");
					LogOutButton.setEnabled(true);
				}
				else if (user_List != null)//general condition
				{
				for (int i = 1; i <= size; i++) {
					userFlexTable.setText(i, 0, user_List.get(i - 1).getName());
					
					statusType status = user_List.get(i - 1).retrieveStatus();
					if (status != null)
						userFlexTable.setText(i, 1, status.toString());
					
					Double money = user_List.get(i - 1).getMoney();
					
					if (money != null)
					{
						if (i == 2)
							userFlexTable.setText(i, 2, "N/A");
						else
						userFlexTable.setText(i, 2, money.toString());
					}
					Double bidAmount = user_List.get(i - 1).retrieveBidAmount();
					if (bidAmount != null)
						userFlexTable.setText(i, 3, bidAmount.toString());
					
					Integer cardNumber = user_List.get(i - 1).retrieveCardNumbers();
					if (cardNumber != null)
						userFlexTable.setText(i, 4, cardNumber.toString());
				}

/*					userFlexTable.setText(5, 0, UserList.get(0).getName()
							+ " says: ");
					userFlexTable.setText(5, 1, "my message");*/
				
				}//end else
				
			}

		});
		
	}
  
  private void drawTable(int i) {

	}
  
  private void setReady(){
	  svc.setReady(new AsyncCallback<Void>()
			  {
		  		
				
				public void onFailure(Throwable arg0) {
					
					ReadyButton.setEnabled(true);
				}

				
				public void onSuccess(Void arg0) {
					
					userFlexTable.setText(1, 1, "Ready");
					bidFirstTime = true;
				}
		  
			  }
			  );
  }
 private void bid(double money){
	  
	  svc.bid(25.0, new AsyncCallback<Card>()
			  {

				
				public void onFailure(Throwable arg0) {
					
					bidButton.setEnabled(true);
				}

				
				public void onSuccess(Card myCard) {
					/*bidMoney += 25;
					myMoney = myMoney - 25;
					userFlexTable.setText(1, 2, myMoney + "");
					userFlexTable.setText(1, 3, bidMoney+"");*/
					myCardCount++;
					userFlexTable.setText(1, 5, myCard.toString());
					
					afterBid = true;
				    myCurrentCard = myCard;
				    
				    bidFirstTime = false;
				    userFlexTable.setText(1, 1, "Bid");
				    onModuleLoad();
				    bidButton.setEnabled(false);
				    ReadyButton.setEnabled(false);
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
				    
				    bidAfter = true;
				    
				}
		  
			  });
  }
 private void doubledown()
 {
	 svc.doubledown(new AsyncCallback<Card>()
			 {

				
				public void onFailure(Throwable arg0) {
					// TODO Auto-generated method stub
					DoubledownButton.setEnabled(true);
				}

				
				public void onSuccess(Card myGotCard) {
					myCardCount++;
					userFlexTable.setText(1, 4+myCardCount, myGotCard.toString());
					myCurrentCard = myGotCard;
					//userFlexTable.setText(1, 1, "DoubleDown");
					onModuleLoad();
					ReadyButton.setEnabled(false);
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					  
					  doubledownAfter = true;
					
				}
		 
			 });
 }
 private void hit()
 {
	 svc.hit(new AsyncCallback<Card>()
			 {

				
				public void onFailure(Throwable arg0) {
					// TODO Auto-generated method stub
					HitButton.setEnabled(true);
				}

				
				public void onSuccess(Card myGotCard) {
					
					myCardCount++;
					userFlexTable.setText(1, 4+myCardCount, myGotCard.toString());
					myCurrentCard = myGotCard;
					userFlexTable.setText(1, 1, "Hit");
					onModuleLoad();
					ReadyButton.setEnabled(false);
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					  
					  hitAfter = true;
				}
		 
			 });
 }
 private void stand()
 {
	  svc.stand(new AsyncCallback<Void>()
			  {

				
				public void onFailure(Throwable arg0) {
					StandButton.setEnabled(true);
					
				}

				
				public void onSuccess(Void arg0) {
					
					userFlexTable.setText(1, 1, "Stand");
					onModuleLoad();
					ReadyButton.setEnabled(false);
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					  
					  standAfter = true;
				}

				
		  
			  });
 }

  private void surrender()
  {
	  svc.surrender(new AsyncCallback<Void>()
			  {

				
				public void onFailure(Throwable arg0) {
					SurrenderButton.setEnabled(true);
					
				}

				
				public void onSuccess(Void arg0) {
					
					userFlexTable.setText(1, 1, "Surrender");
					
					onModuleLoad();
					ReadyButton.setEnabled(false);
					 HitButton.setEnabled(false);
					  StandButton.setEnabled(false);
					  DoubledownButton.setEnabled(false);
					  SplitButton.setEnabled(false);
					  SurrenderButton.setEnabled(false);
					  
					  surrenderAfter = true;
				}
		  
			  });
  }
  
  private void modifyUser(User user1)
  {
	    final String modify_username = ModifyUserNameBox.getText();
		final String modify_password = ModifyUserPasswordBox.getText();
		final double modify_money = Double.valueOf(ModifyUserMoneyBox.getText().trim()).doubleValue();
		user1.setName(modify_username);
		user1.setPassword(modify_password);
		user1.setMoney(modify_money);
		
	  svc.modifyUser(user1, new AsyncCallback<Void>()
			  {

				
				public void onFailure(Throwable arg0) {
					Window.alert("Failed to modify user:\n" +arg0.getMessage());
				}

				
				public void onSuccess(java.lang.Void arg0) {
					Window.alert("Modify Successful !");
					getUserList();
					Page = 4;
					onModuleLoad();
				}
		  
			  });
  }

  private void deleteUser(User user1)
  {
	  
		
	  svc.deleteUser(user1, new AsyncCallback<Void>()
			  {

				
				public void onFailure(Throwable arg0) {
					Window.alert("Failed to delete user:\n" +arg0.getMessage());
					Page = 1;
					onModuleLoad();
				}

				
				public void onSuccess(java.lang.Void arg0) {
					Window.alert("Delete User "+ deletedUserNum +" Successful !");
					Page = 5;
					getUserList();
					onModuleLoad();
					
				}
		  
			  });
  }
  
  private void refreshTable() {
		int size = UserList.size();
		for (int i = 1; i <= size; i++) {
			
			statusType status = UserList.get(i - 1).retrieveStatus();
			if (status != null)
				userFlexTable.setText(i, 1, status.toString());
			
			Double money = UserList.get(i - 1).getMoney();
			
			if (money != null)
			{
				if (i == 2)
					userFlexTable.setText(i, 2, "N/A");
				else
				userFlexTable.setText(i, 2, money.toString());
			}
			Double bidAmount = UserList.get(i - 1).retrieveBidAmount();
			if (bidAmount != null)
				userFlexTable.setText(i, 3, bidAmount.toString());
			
			Integer cardNumber = UserList.get(i - 1).retrieveCardNumbers();
			if (cardNumber != null)
				userFlexTable.setText(i, 4, cardNumber.toString());
			
/*			userFlexTable.setText(i, 1, UserList.get(i - 1).retrieveStatus()
					.toString());
			userFlexTable.setText(i, 2, UserList.get(i - 1).getMoney()
					.toString());
			userFlexTable.setText(i, 3, UserList.get(i - 1).retrieveBidAmount()
					.toString());
			userFlexTable.setText(i, 4, UserList.get(i - 1)
					.retrieveCardNumbers()
					+ "");*/
			if (i != 1) {
				if (UserList.get(i - 1).retrieveCardNumbers() != 0) {
					Integer total = UserList.get(i - 1).retrieveCardNumbers();
					if (total == null)
						total = -1;
					for (int j = 0; j <= total; j++)
						userFlexTable.setText(i, j + 5, "*");
				}
			}
		}

	}
  private void showResult()
  {
//	  for (int i = 1; i<= 4; i++)
//	  {
//		  userFlexTable.setText(i, 1, UserList.get(i-1).retrieveStatus().toString());
//		  userFlexTable.setText(i, 2, UserList.get(i-1).getMoney().toString());
//		  userFlexTable.setText(i, 3, UserList.get(i-1).retrieveBidAmount().toString());
//		  userFlexTable.setText(i, 4, UserList.get(i-1).retrieveCardNumbers()+"");
//		  //userFlexTable.setText(i, 5, UserList.get(i-1).);
//	  }
	  
	  
	  
	  
  }
  
  private void joinTable() {
		svc.joinTable(new AsyncCallback<Void>() {

			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub

			}

			public void onSuccess(Void arg0) {
				Window.alert("You join a table !");
				getUserList();
				Page = 3;
				onModuleLoad();
			}

		});

	}

	private void reset() {
		myCardCount = 0;
		afterBid = false;
		bidButton.setEnabled(false);
		bidFirstTime = false;
		
		for (int i = 1; i <= 4; i++) {
			userFlexTable.setText(i, 5, "");
			userFlexTable.setText(i, 6, "");
			userFlexTable.setText(i, 7, "");
			userFlexTable.setText(i, 8, "");
			userFlexTable.setText(i, 9, "");
		}
	}

	private String Face(Card theCard)
	{
		String face = new String();
		String array[] = { "Ace", "Deuce", "Three", "Four", "Five", "Six",
			 "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
		for (int i=0;i<=12;i++)
		{
		if (theCard.toString().startsWith(array[i]))
		{
			if (i==0)
			face = "A";
			else if (i==10)
				face = "J";
			else if (i==11)
				face = "Q";
			else if (i==12)
				face = "K";
			else
				face = (i+1)+"";
				
		}
		}
		
		return face;
	}
	private String Suit(Card theCard)
	{
		String suit = new String();
		String array[] = { "Hearts", "Diamonds", "Clubs", "Spades" };
			for (int i=0;i<=3;i++)
			{
			if (theCard.toString().endsWith(array[i]))
			{
				if (i == 0)
					suit = "Heart";
				else if (i == 1)
					suit = "Diamond";
				else if (i == 2)
					suit = "Club";
				else
					suit = "Spade";
					
			}
			}
		return suit;
	}
	
}// end Main

